import { reqGetDefaultTags } from '@/api/hosting-style';
let eventChannel: WechatMiniprogram.EventChannel;

Page({
  data: {
    maxTagCount: 3,
    defaultTagList: [] as string[],
    customTagList: [] as string[],
    selectedTagList: [] as string[],
  },
  async onLoad(options) {
    eventChannel = this.getOpenerEventChannel();

    const defaultTagList = (await reqGetDefaultTags()).data;
    const selectedTagList = JSON.parse(options.selectedTagList || '[]');
    const customTagList = selectedTagList.filter((tag: string) => !defaultTagList.includes(tag));
    this.setData({
      defaultTagList,
      customTagList,
      selectedTagList,
    });
  },
  onSelectTag(e: WechatMiniprogram.TouchEvent) {
    const tag = e.currentTarget.dataset.tag;
    if (this.data.selectedTagList.includes(tag)) return;

    if (this.data.selectedTagList.length >= this.data.maxTagCount) {
      wx.showToast({
        title: `最多只能选择${this.data.maxTagCount}个标签`,
        icon: 'none',
      });
      return;
    }

    this.setData({
      selectedTagList: [...this.data.selectedTagList, tag],
    });
    eventChannel?.emit('updateTags', this.data.selectedTagList);
  },
  onClickAdd() {
    if (this.data.selectedTagList.length >= this.data.maxTagCount) {
      wx.showToast({
        title: `最多只能选择${this.data.maxTagCount}个标签，请先删除标签`,
        icon: 'none',
      });
      return;
    }

    const dialog = this.selectComponent('#add-tag-dialog');
    dialog.open();
  },
  onConfirmAddTag(e: WechatMiniprogram.CustomEvent) {
    const newTag = e.detail.value;
    if (this.data.customTagList.includes(newTag)) {
      wx.showToast({
        title: '标签已存在',
        icon: 'none',
      });
      return;
    }

    this.setData({
      customTagList: [...this.data.customTagList, newTag],
      selectedTagList: [...this.data.selectedTagList, newTag],
    });
    eventChannel?.emit('updateTags', this.data.selectedTagList);
  },
  onClickDeleteTag(e: WechatMiniprogram.TouchEvent) {
    const tag = e.currentTarget.dataset.tag;
    this.setData({
      customTagList: this.data.customTagList.filter((item: string) => item !== tag),
      selectedTagList: this.data.selectedTagList.filter((item: string) => item !== tag),
    });
    eventChannel?.emit('updateTags', this.data.selectedTagList);
  },
});
